package com.future.biz;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import com.future.dao.DepartmentDAO;
import com.future.dao.FirstFillBlankDAO;
import com.future.dao.InforRateDAO;
import com.future.dao.InforShareAnswerDAO;
import com.future.dao.InformationDAO;
import com.future.dao.OfficeDAO;
import com.future.dao.SecondFillBlankDAO;
import com.future.dao.ServicesAnswerTotleDAO;
import com.future.dao.ServicesDAO;
import com.future.dao.ShareTotleDAO;
import com.future.dao.UserDAO;
import com.future.dbutils.TransactionUtils;
import com.future.model.bo.InforRateGridBO;
import com.future.model.bo.LocalSurveyBO;
import com.future.model.bo.ShareTotleBO;
import com.future.model.bo.ShareTotleGridBO;
import com.future.model.bo.ShareTotleGridWarpBO;
import com.future.model.bo.UserBO;
import com.future.model.po.FirstFillBlankModel;
import com.future.model.po.InforRateModel;
import com.future.model.po.InformationModel;
import com.future.model.po.ServicesAnswerTotleModel;
import com.future.model.po.ServicesModel;
import com.future.model.po.ShareTotleModel;

/**
 * 第一部分调查表业务逻辑
 * 
 * @author FutureAdmin
 * 
 */
public class LocalSurveyBIZ {

	private static Logger logger = LogManager.getLogger(LocalSurveyBIZ.class);
	
	public boolean updateLocalSurvey(FirstFillBlankModel firstFillBlankModel,List<InforRateModel> inforRateModels,
			List<ShareTotleModel> shareTotleModels, List<ServicesAnswerTotleModel> servicesAnswerTotleModels){
		boolean flag = true;
		boolean temp = true;
		boolean para = true;
		boolean isNot = true;
		TransactionUtils.startTransaction();
		flag = this.updateFirstFillBlankModel(firstFillBlankModel);
		temp = this.updateInforRateModel(inforRateModels);
		para = this.updateShareTotleModel(shareTotleModels);
		isNot = this.updateServicesAnswerTotleModels(servicesAnswerTotleModels);
		TransactionUtils.commitTransaction();
		if (flag&&temp&&para&&isNot) {
			return true;
		} else {
			return false;
		}
	}
	/**
	 * 修改第一部分  第一张表格
	 * @param shareTotleModels
	 * @return true为修改成功，false为修改失败
	 */
	private  boolean updateServicesAnswerTotleModels(List<ServicesAnswerTotleModel> models){
		boolean flag = true;
		ServicesAnswerTotleDAO dao = new ServicesAnswerTotleDAO(TransactionUtils.getConnection());
		for (ServicesAnswerTotleModel model : models) {
			flag = dao.update(model);
			if (!flag) {
				break;
			}
		}
		return flag;
	}
	/**
	 * 修改第一部分  第三张表格
	 * @param shareTotleModels
	 * @return true为修改成功，false为修改失败
	 */
	private  boolean updateShareTotleModel(List<ShareTotleModel> shareTotleModels){
		boolean flag = true;
		ShareTotleDAO shareTotleDAO = new ShareTotleDAO(TransactionUtils.getConnection());
		for (ShareTotleModel shareTotleModel : shareTotleModels) {
			flag = shareTotleDAO.update(shareTotleModel);
			if (!flag) {
				break;
			}
		}
		return flag;
	}
	
	/**
	 * 修改第一部分 第二张表
	 * @param inforRateModels
	 * @return true为修改成功，false为修改失败
	 */
	private boolean updateInforRateModel(List<InforRateModel> inforRateModels){
		boolean flag = true;
		InforRateDAO inforRateDAO = new InforRateDAO(TransactionUtils.getConnection());
		for (InforRateModel inforRateModel : inforRateModels) {
			flag = inforRateDAO.update(inforRateModel);
			if (!flag) {
				break;
			}
		}
		return flag;
	}
	/**
	 * 修改第一部分填空题
	 * @param firstFillBlankModel
	 * @return true为修改成功，false为修改失败
	 */
	private boolean updateFirstFillBlankModel(FirstFillBlankModel firstFillBlankModel){
		FirstFillBlankDAO firstFillBlankDao = new FirstFillBlankDAO(TransactionUtils.getConnection());
		return firstFillBlankDao.modifyByUserId(firstFillBlankModel);
	}

	public LocalSurveyBO generatSurveyByUser(UserBO userBo) {
		LocalSurveyBO localSurveyBo = new LocalSurveyBO();

		Integer userId = userBo.getUser().getId();
		if (!isComplete(userId)) {
			logger.debug("正在进行地方调查表初始化");
			initSurvey(userBo);
		}

		localSurveyBo.setUserBo(userBo);
		FirstFillBlankDAO firstFillBlankDao = new FirstFillBlankDAO();
		FirstFillBlankModel firstFillBlankModel = firstFillBlankDao.findByUserId(userId).get(0);
		localSurveyBo.setFirstFillBlankModel(firstFillBlankModel);

		GenerateGrid<InforRateGridBO> inforRateGrid = new InforRateGrid();

		List<InforRateGridBO> inforRateGridList = inforRateGrid.loadGrid(userBo);
		localSurveyBo.setInforRateGrid(inforRateGridList);

		GenerateGrid<ShareTotleGridBO> shareTotleGrid = new ShareTotleGrid();
		List<ShareTotleGridBO> shareTotleGridList = shareTotleGrid.loadGrid(userBo);
		List<ShareTotleGridWarpBO> shareTotleGridWarpList = new ArrayList<ShareTotleGridWarpBO>();
		List<ShareTotleBO> subList = null;
		// 添加一个外部游标
		int currentIndex = 0;
		for (int index = currentIndex; index < shareTotleGridList.size(); index = ++currentIndex) {
			ShareTotleGridWarpBO bo = new ShareTotleGridWarpBO();
			bo.setDepartment(shareTotleGridList.get(index).getShareDepartmentName());
			subList = new ArrayList<ShareTotleBO>();
			for (int tempIndex = currentIndex; tempIndex < shareTotleGridList.size(); tempIndex = ++currentIndex) {
				Integer tempShareDepartmentId = shareTotleGridList.get(tempIndex).getShareDepartmentId();
				if (!tempShareDepartmentId.equals(shareTotleGridList.get(index).getShareDepartmentId())) {
					index = --currentIndex;
					break;
				}
				ShareTotleBO temp = new ShareTotleBO();
				temp.setServicesId(shareTotleGridList.get(tempIndex).getInforid());
				temp.setServicesName(shareTotleGridList.get(tempIndex).getInformation());
				temp.setCount(shareTotleGridList.get(tempIndex).getTotle());
				subList.add(temp);
			}
			bo.setShareTotle(subList);
			shareTotleGridWarpList.add(bo);
		}

		// localSurveyBo.setShareTotleGrid(shareTotleGridList);
		localSurveyBo.setShareTotleGrid(shareTotleGridWarpList);
		List<ServicesAnswerTotleModel> servicessum = this.getServicessum(userBo);
		localSurveyBo.setServicessum(servicessum);

		return localSurveyBo;
	}
	
	/**
	 * 获得第一部分地方调查第七题表格中的数据
	 * @param userBo
	 * @return
	 */
	private List<ServicesAnswerTotleModel> getServicessum(UserBO userBo){
		ServicesAnswerTotleDAO answerTotleDAO = new ServicesAnswerTotleDAO();
		return  answerTotleDAO.findByUserId(userBo.getUser());
	}

	private void initSurvey(UserBO userBo) {

		Integer userId = userBo.getUser().getId();
		TransactionUtils.startTransaction();

		initFirstFillBlank(userBo);
		initServicesAnswerTotle(userId);
		initInforRate(userBo);
		initShareTotle(userBo);

		TransactionUtils.commitTransaction();
	}

	/**
	 * @param userId
	 */
	private void initServicesAnswerTotle(Integer userId) {
		ServicesAnswerTotleDAO servicesAnswerTotleDao = new ServicesAnswerTotleDAO(TransactionUtils.getConnection());
		ServicesAnswerTotleModel servicesAnswerTotleModel = null;
		ServicesDAO servicesDao = new ServicesDAO();
		Iterator<ServicesModel> servicesIter = servicesDao.findAll().iterator();
		while (servicesIter.hasNext()) {
			servicesAnswerTotleModel = new ServicesAnswerTotleModel();
			servicesAnswerTotleModel.setServicesid(servicesIter.next().getId());
			servicesAnswerTotleModel.setUserid(userId);
			servicesAnswerTotleDao.save(servicesAnswerTotleModel);
		}
	}

	/**
	 * @param userId
	 */
	private void initShareTotle(UserBO userBo) {
		ShareTotleDAO shareTotleDao = new ShareTotleDAO(TransactionUtils.getConnection());
		InformationDAO informationDao = new InformationDAO();
		ShareTotleModel shareTotleModel = null;
		ShareTotleGrid shareTotleGrid = new ShareTotleGrid();
		Map<Integer, ShareTotleGridBO> shareInforTotleMap = shareTotleGrid.generateGrid(userBo);
		Iterator<InformationModel> iter = informationDao.findAll().iterator();
		while (iter.hasNext()) {
			InformationModel m = iter.next();
			shareTotleModel = new ShareTotleModel();
			shareTotleModel.setInforid(m.getId());
			shareTotleModel.setUserId(userBo.getUser().getId());
			shareTotleModel.setTotle(shareInforTotleMap.get(m.getId()).getTotle());
			shareTotleDao.save(shareTotleModel);
		}
	}

	/**
	 * @param userId
	 */
	private void initInforRate(UserBO userBo) {
		Integer userId = userBo.getUser().getId();
		InforRateDAO inforRateDao = new InforRateDAO(TransactionUtils.getConnection());
		InforRateModel inforRateModel = null;
		InforRateGrid inforRateGrid = new InforRateGrid();
		Map<Integer, InforRateGridBO> inforRateGridMap = inforRateGrid.generateGrid(userBo);
		for (int departmentId = 2; departmentId <= 33; departmentId++) {
			inforRateModel = new InforRateModel();
			inforRateModel.setDepartmentId(departmentId);
			inforRateModel.setUserid(userId);
			inforRateModel.setRate(inforRateGridMap.get(departmentId).getRate());
			inforRateDao.save(inforRateModel);
		}
	}

	/**
	 * @param userId
	 */
	private void initFirstFillBlank(UserBO userBo) {
		
		SecondFillBlankDAO dao = new SecondFillBlankDAO();
		FirstFillBlankDAO firstFillBlankDao = new FirstFillBlankDAO();
		FirstFillBlankModel firstFillBlankModel = new FirstFillBlankModel();
		firstFillBlankModel.setUserId(userBo.getUser().getId());
		
		Map<String, Object> map = dao.getStatistical(userBo.getArea().getId()).get(0);
		firstFillBlankModel.setItem0101(map.get("item0101")!=null?Integer.valueOf(map.get("item0101")+""):0);
		firstFillBlankModel.setItem0102(map.get("item0102")!=null?Integer.valueOf(map.get("item0102")+""):0);
		firstFillBlankModel.setItem0201(map.get("item0201")!=null?Integer.valueOf(map.get("item0201")+""):0);
		firstFillBlankModel.setItem0202(map.get("item0202")!=null?Float.valueOf(map.get("item0202")+""):0);
		firstFillBlankModel.setItem0203(map.get("item0203")!=null?Integer.valueOf(map.get("item0203")+""):0);
		firstFillBlankModel.setItem0204(map.get("item0204")!=null?Float.valueOf(map.get("item0204")+""):0);
		firstFillBlankModel.setItem0205(map.get("item0205")!=null?Float.valueOf(map.get("item0205")+""):0);
		firstFillBlankModel.setItem0206(map.get("item0206")!=null?Float.valueOf(map.get("item0206")+""):0);
		firstFillBlankModel.setItem0301(map.get("item0301")!=null?Float.valueOf(map.get("item0301")+""):0);
		firstFillBlankModel.setItem0302(map.get("item0302")!=null?Float.valueOf(map.get("item0302")+""):0);

		UserDAO userDao = new UserDAO();
		Integer countUserInSameArea = userDao.countUserInSameArea(userBo.getArea().getId()).size();
		firstFillBlankModel.setItem0802(countUserInSameArea);
		firstFillBlankModel.setItem0902(countUserInSameArea);

		OfficeDAO officeDao = new OfficeDAO();
		Integer countOffice = officeDao.countOfficeByAreaId(userBo.getArea().getId()).size();
		firstFillBlankModel.setItem0803(countOffice);
		Integer item0804 = officeDao.countOfficeServicesByAreaId(userBo.getArea().getId()).size();
		firstFillBlankModel.setItem0804(item0804);
		Float item0806 = null;
		if(countOffice!=null&&countOffice>0){
			item0806 = (100*(Float.valueOf(item0804)))/Float.valueOf(countOffice);
		}
		firstFillBlankModel.setItem0806(item0806);
		DepartmentDAO departmentDAO = new DepartmentDAO();
		
		Integer item0805 = departmentDAO.findByareaID(userBo.getArea().getId());
		firstFillBlankModel.setItem0805(item0805);

		InforShareAnswerDAO inforShareAnswerDao = new InforShareAnswerDAO();
		Iterator<Map<String, Object>> item09Iter = inforShareAnswerDao.countShareType(userBo.getArea().getId())
				.iterator();
		Map<String, Object> m = item09Iter.next();
		firstFillBlankModel.setItem0904(compareMax(m));

		firstFillBlankDao.save(firstFillBlankModel);
	}

	private boolean isComplete(Integer userId) {
		boolean flag = false;
		FirstFillBlankDAO firstFillBlankDao = new FirstFillBlankDAO();
		Integer firstFillBlankListSize = firstFillBlankDao.findByUserId(userId).size();

		InforRateDAO inforRateDao = new InforRateDAO();
		Integer inforRateListSize = inforRateDao.findByUserId(userId).size();

		ShareTotleDAO shareTotleDao = new ShareTotleDAO();
		Integer shareTotleListSize = shareTotleDao.findByUserId(userId).size();

		ServicesAnswerTotleDAO servicesAnswerTotleDao = new ServicesAnswerTotleDAO();
		Integer servicesAnswerTotleListSize = servicesAnswerTotleDao.findByUserId(userId).size();
		if (firstFillBlankListSize == 1 && inforRateListSize == 32 && shareTotleListSize == 161
				&& servicesAnswerTotleListSize == 295) {
			flag = true;
		} else {
			deleteSurveyData(userId, firstFillBlankDao, inforRateDao, shareTotleDao, servicesAnswerTotleDao);
			logger.debug("问卷初始化失败,正在删除数据,等待初始化");
		}
		return flag;
	}

	private void deleteSurveyData(Integer userId,
			FirstFillBlankDAO firstFillBlankDao,
			InforRateDAO inforRateDao,
			ShareTotleDAO shareTotleDao,
			ServicesAnswerTotleDAO servicesAnswerTotleDao) {
		firstFillBlankDao.deleteByUserId(userId);
		inforRateDao.deleteByUserId(userId);
		shareTotleDao.deleteByUserId(userId);
		servicesAnswerTotleDao.deleteByUserId(userId);
	}

	protected String compareMax(Map<String, Object> map) {

		Integer countA = Integer.valueOf(map.get("A") == null ? "0" : map.get("A").toString());
		Integer countB = Integer.valueOf(map.get("B") == null ? "0" : map.get("B").toString());
		Integer countC = Integer.valueOf(map.get("C") == null ? "0" : map.get("C").toString());

		if (countA == 0 && countB == 0 && countC == 0) {
			return "";
		}

		StringBuffer sb = new StringBuffer("");
		if (countA >= countB && countA >= countC) {
			sb.append("A");
			if (countA == countB) {
				sb.append("B");
			}
			if (countA == countC) {
				sb.append("C");
			}
		} else if (countB >= countC && countB >= countA) {
			sb.append("B");
			if (countB == countA) {
				sb.append("A");
			}
			if (countB == countC) {
				sb.append("C");
			}
		} else {
			sb.append("C");
			if (countC == countA) {
				sb.append("A");
			}
			if (countC == countB) {
				sb.append("B");
			}
		}
		return sb.toString();
	}
}
